package edu.task.snake.controller;

import edu.task.snake.model.Frog;


public class FrogController extends Thread implements Runnable {

    private static final int sleepInMilliseconds = 1000;
    private Frog model;
    private GameEngine gameEngine;


    public FrogController(Frog model, GameEngine gameEngine) {
        this.model = model;
        this.gameEngine = gameEngine;
    }


    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                sleep(sleepInMilliseconds);
            } catch (InterruptedException e) {
                this.stop();
                e.printStackTrace();
            }
            move();
        }
    }

    private void move() {
        int x = model.getX();
        int y = model.getY();
        boolean freeWayXForward = false;
        boolean freeWayXReverse = false;
        boolean freeWayYForward = false;
        boolean freeWayYReverse = false;

        synchronized (gameEngine.getLock()) {
            if (x + 1 < gameEngine.getCellWidth() && (gameEngine.getArena().getFromArena(x + 1, y) == null))
                freeWayXForward = true;
            if (x - 1 >= 0 && (gameEngine.getArena().getFromArena(x - 1, y) == null)) freeWayXReverse = true;
            if (y + 1 < gameEngine.getCellHeight() && (gameEngine.getArena().getFromArena(x, y + 1) == null))
                freeWayYForward = true;
            if (y - 1 >= 0 && (gameEngine.getArena().getFromArena(x, y - 1) == null)) freeWayYReverse = true;

            if (Math.random() < 0.5 && freeWayXForward) {
                x += 1;
            } else if (freeWayXReverse) {
                x -= 1;
            }

            if (Math.random() < 0.5 && freeWayYForward) {
                y += 1;
            } else if (freeWayYReverse) {
                y -= 1;
            }
            gameEngine.getArena().setToArena(model.getX(), model.getY(), null);
            gameEngine.getArena().setToArena(x,y,model);
            model.setPosition(x, y);

        }

    }
}
